import { toast } from './util'
import type { AnyObject } from '@/common/types'

// 清除缓存
export async function clearCache() {
  let fileSizeString:string
  plus.cache.calculate((size:any) => {
    const sizeCache = parseInt(size)
    if (!sizeCache) {
      fileSizeString = '0B'
    } else if (sizeCache < 1024) {
      fileSizeString = sizeCache + 'B'
    } else if (sizeCache < 1048576) {
      fileSizeString = (sizeCache / 1024).toFixed(2) + 'KB'
    } else if (sizeCache < 1073741824) {
      fileSizeString = (sizeCache / 1048576).toFixed(2) + 'MB'
    } else {
      fileSizeString = (sizeCache / 1073741824).toFixed(2) + 'GB'
    }
    const os = plus.os.name
    if (os === 'Android') {
      const main = plus.android.runtimeMainActivity()
      const sdRoot = main.getCacheDir()
      const files = plus.android.invoke(sdRoot, 'listFiles')
      const len = files.length
      for (let i = 0; i < len; i++) {
        const filePath = '' + files[i] // 没有找到合适的方法获取路径，这样写可以转成文件路径
        plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
          if (entry.isDirectory) {
            entry.removeRecursively((entry) => { // 递归删除其下的所有文件及子目录
              toast(`已清理${fileSizeString}缓存`)
            }, (e) => {
              console.log(e.message)
            })
          } else {
            entry.remove()
          }
        }, function(e) {
          console.log('文件路径读取失败')
        })
      }
    } else { // ios
      plus.cache.clear(function() {
        toast(`已清理${fileSizeString}缓存`)
      })
    }
  })
}

// 获取当前版本
export function getVersion():Promise<AnyObject> {
  return new Promise((resolve, reject) => {
    plus.runtime.getProperty(plus.runtime.appid, function(info) {
      resolve(info)
    })
  })
}

// 下载新版本
export function doUpdateVersion(url:string, callback?:(progress:number)=>void) {
  const downloadTask = uni.downloadFile({ // 执行下载
    url, // 下载地址
    success: downloadResult => { // 下载成功
      const path = downloadResult.tempFilePath
      if (url.includes('.wgt')) {
        plus.runtime.install(path, {
          force: true
        }, () => {
          plus.runtime.restart()
        })
      } else {
        plus.runtime.install(path)
      }
    }
  })

  downloadTask.onProgressUpdate((res) => {
    callback && callback(res.progress)
  })
}
